package cn.edu.ctbu.scoremg.service;

import cn.edu.ctbu.scoremg.constant.REnum;
import cn.edu.ctbu.scoremg.dao.TeacherRepository;
import cn.edu.ctbu.scoremg.entity.Teacher;
import cn.edu.ctbu.scoremg.exception.RException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TeacherService {

    @Autowired
    private TeacherRepository teacherRepository;

    public List<Teacher> getAll() {
        return teacherRepository.findAll();
    }

    public Page<Teacher> getAll(Pageable pageable) {
        return teacherRepository.findAll(pageable);
    }

    public Page<Teacher> getAll(Example<Teacher> example, Pageable pageable) {
        return teacherRepository.findAll(example, pageable);
    }

    /**
     * 按id进行查询
     * @param id 主键，整数
     * @return 教师对象
     */
    public Teacher findById(Integer id) {
        return teacherRepository.findById(id).orElse(null);
    }

    /**
     * 按姓名进行查询
     * @param name 教师姓名
     * @return 教师列表
     */
    public List<Teacher> findByName(String name) {
        return teacherRepository.findByNameLike(name);
    }

    /**
     * 按工号和密码查询
     * @param no 教师工号
     * @param password 密码
     * @return 教师列表
     */
    public List<Teacher> findByNoAndPassword(String no, String password) {
        return teacherRepository.findByNoAndPassword(no, password);
    }

    /**
     * 新增教师
     * @param teacher 教师对象
     * @return 保存后的教师对象
     */
    public Teacher add(Teacher teacher) {
        return teacherRepository.save(teacher);
    }

    /**
     * 更新教师信息
     * @param teacher 教师对象
     * @return 更新后的教师对象
     */
    public Teacher update(Teacher teacher) {
        return teacherRepository.save(teacher);
    }

    /**
     * 删除教师
     * @param id 教师ID
     */
    public void delete(Integer id) {
        teacherRepository.deleteById(id);
    }

    /**
     * 验证教师工号和密码
     * @param no 教师工号
     * @param password 密码
     * @return 验证通过的教师对象
     * @throws Exception 验证失败抛出异常
     */
    public Teacher validateNoAndPassword(String no, String password) throws Exception {
        List<Teacher> teachers = teacherRepository.findByNo(no);
        if (teachers.size() > 0) {
            Teacher teacher = teachers.get(0);
            if (teacher.getPassword().equals(password)) {
                return teacher;
            } else {
                throw new RException(REnum.LOGIN_ERR);
            }
        } else {
            throw new RException(REnum.LOGIN_ERR);
        }
    }

    /**
     * 批量删除教师
     * @param ids 教师ID列表
     */
    public void deleteBatch(List<Integer> ids) {
        teacherRepository.deleteAllById(ids);
    }
}